package com.mfw.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mfw.springboot.common.DataGroupByDateDTO;
import com.mfw.springboot.common.ErrorCode;
import com.mfw.springboot.constant.CommonConstant;
import com.mfw.springboot.exception.ThrowUtils;
import com.mfw.springboot.mapper.TrainingRuleMapper;
import com.mfw.springboot.model.dto.trainingRule.TrainingRuleQueryRequest;
import com.mfw.springboot.model.entity.TrainingRule;
import com.mfw.springboot.model.entity.User;
import com.mfw.springboot.model.vo.TrainingRuleVO;
import com.mfw.springboot.model.vo.UserVO;
import com.mfw.springboot.service.TrainingRuleService;
import com.mfw.springboot.service.UserService;
import com.mfw.springboot.utils.DateUtils;
import com.mfw.springboot.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 训练规则服务实现
 *
 * @author mfw
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@Service
@Slf4j
public class TrainingRuleServiceImpl extends ServiceImpl<TrainingRuleMapper, TrainingRule> implements TrainingRuleService {

    @Resource
    private UserService userService;

    /**
     * 校验数据
     *
     * @param trainingRule
     * @param add          对创建的数据进行校验
     */
    @Override
    public void validTrainingRule(TrainingRule trainingRule, boolean add) {
        ThrowUtils.throwIf(trainingRule == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        String ruleName = trainingRule.getRuleName();
        String description = trainingRule.getDescription();
        String content = trainingRule.getContent();
        Integer num = trainingRule.getNum();
        Date startTime = trainingRule.getStartTime();
        Date endTime = trainingRule.getEndTime();


        // 创建数据时，参数不能为空
        if (add) {
            // 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(ruleName), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(StringUtils.isBlank(content), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(num == 0 || num < 0, ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(startTime == null, ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(endTime == null, ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        // 补充校验规则
        if (StringUtils.isNotBlank(ruleName)) {
            ThrowUtils.throwIf(ruleName.length() > 10, ErrorCode.PARAMS_ERROR, "名称过长");
        }
        if (StringUtils.isNotBlank(description)) {
            ThrowUtils.throwIf(description.length() > 10, ErrorCode.PARAMS_ERROR, "描述过长");
        }
        if (StringUtils.isNotBlank(content)) {
            ThrowUtils.throwIf(content.length() > 80, ErrorCode.PARAMS_ERROR, "内容过长");
        }
        if (num != null) {
            ThrowUtils.throwIf(num < 0, ErrorCode.PARAMS_ERROR, "数量过长");
        }
    }

    /**
     * 获取查询条件
     *
     * @param trainingRuleQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<TrainingRule> getQueryWrapper(TrainingRuleQueryRequest trainingRuleQueryRequest) {
        QueryWrapper<TrainingRule> queryWrapper = new QueryWrapper<>();
        if (trainingRuleQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = trainingRuleQueryRequest.getId();
        String ruleName = trainingRuleQueryRequest.getRuleName();
        String description = trainingRuleQueryRequest.getDescription();
        String content = trainingRuleQueryRequest.getContent();
        Long userId = trainingRuleQueryRequest.getUserId();
        String sortField = trainingRuleQueryRequest.getSortField();
        String sortOrder = trainingRuleQueryRequest.getSortOrder();

        // 补充需要的查询条件
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(ruleName), "rule_name", ruleName);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);

        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "user_id", userId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取训练规则封装
     *
     * @param trainingRule
     * @param request
     * @return
     */
    @Override
    public TrainingRuleVO getTrainingRuleVO(TrainingRule trainingRule, HttpServletRequest request) {
        // 对象转封装类
        TrainingRuleVO trainingRuleVO = TrainingRuleVO.objToVo(trainingRule);

        // 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = trainingRule.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        trainingRuleVO.setUser(userVO);
        // endregion

        return trainingRuleVO;
    }

    /**
     * 分页获取训练规则封装
     *
     * @param trainingRulePage
     * @param request
     * @return
     */
    @Override
    public Page<TrainingRuleVO> getTrainingRuleVOPage(Page<TrainingRule> trainingRulePage, HttpServletRequest request) {
        List<TrainingRule> trainingRuleList = trainingRulePage.getRecords();
        Page<TrainingRuleVO> trainingRuleVOPage = new Page<>(trainingRulePage.getCurrent(), trainingRulePage.getSize(), trainingRulePage.getTotal());
        if (CollUtil.isEmpty(trainingRuleList)) {
            return trainingRuleVOPage;
        }
        // 对象列表 => 封装对象列表
        List<TrainingRuleVO> trainingRuleVOList = trainingRuleList.stream().map(trainingRule -> {
            return TrainingRuleVO.objToVo(trainingRule);
        }).collect(Collectors.toList());

        // TODO 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = trainingRuleList.stream().map(TrainingRule::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));

        // 填充信息
        trainingRuleVOList.forEach(trainingRuleVO -> {
            Long userId = trainingRuleVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            trainingRuleVO.setUser(userService.getUserVO(user));
        });
        // endregion

        trainingRuleVOPage.setRecords(trainingRuleVOList);
        return trainingRuleVOPage;
    }

    /**
     * 分按日期分组查询训练规则新增数量
     *
     * @param beginDate 开始时间
     * @param endDate   结束时间
     * @return
     */
    @Override
    public List<DataGroupByDateDTO> countByDay(Date beginDate, Date endDate) {
        QueryWrapper<TrainingRule> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DATE_FORMAT(create_time, '%Y-%m-%d') AS day", "COUNT(1) AS num");
        queryWrapper.ge("create_time", beginDate);
        queryWrapper.le("create_time", endDate);
        queryWrapper.groupBy("day");
        queryWrapper.orderByAsc("day");
        // 执行查询
        List<Map<String, Object>> results = this.baseMapper.selectMaps(queryWrapper);
        // 映射到 DataGroupByDateDTO
        return results.stream().map(result -> {
            DataGroupByDateDTO dto = new DataGroupByDateDTO();
            dto.setDay(DateUtils.parse(result.get("day").toString(), DateUtils.FMT_YMD));
            dto.setNum((Long) result.get("num"));
            return dto;
        }).collect(Collectors.toList());
    }

}
